package controller

import (
	"com.haojuetrace/actualCombat/model"
	"com.haojuetrace/actualCombat/repository"
	"com.haojuetrace/actualCombat/response"
	"com.haojuetrace/actualCombat/vo"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

/*
	分类的创建，修改，删除，查看
	逻辑代码
*/
type IClassifyController interface {
	RestController
}

type ClassifyController struct {
	repository repository.IClassifyRepository
}

func NewClassifyController() IClassifyController {
	classifyRepository := repository.NewClassifyRepository()
	return ClassifyController{repository: classifyRepository}
}

//Create 分类的创建
func (c ClassifyController) Create(ctx *gin.Context) {
	resClassify := vo.ClassifyVo{}
	err := ctx.ShouldBind(&resClassify)
	if err != nil {
		response.Fail(ctx, nil, "请输入分类名称")
		return
	}
	classify := model.Classify{Name: resClassify.Name}
	err = c.repository.Create(&classify)
	if err != nil {
		response.Fail(ctx, nil, "系统繁忙")
		return
	}
	response.Success(ctx, gin.H{"classify": classify}, "创建成功")
	return
}

//Updata 修改分类
func (c ClassifyController) Updata(ctx *gin.Context) {
	resClassify := vo.ClassifyVo{}
	err := ctx.ShouldBind(&resClassify)
	if err != nil {
		response.Fail(ctx, nil, "请输入分类名称")
		return
	}
	//获取path中的参数
	classifyid, err := strconv.Atoi(ctx.Params.ByName("id"))
	if err != nil {
		response.Fail(ctx, nil, "path参数必须包含id")
	}

	exist, classify := c.repository.Select("id", classifyid)

	if !exist {
		response.Fail(ctx, nil, "分类不存在")
		return
	}
	classify.Name = resClassify.Name
	_, err = c.repository.Updata(classify, classifyid)
	if err != nil {
		response.Fail(ctx, nil, "系统繁忙")
	}
	response.Success(ctx, gin.H{"classify": classify}, "修改成功")
	return
}

//Delete 删除分类
func (c ClassifyController) Delete(ctx *gin.Context) {
	//获取path中的参数
	classifyid, err := strconv.Atoi(ctx.Params.ByName("id"))
	if err != nil {
		response.Fail(ctx, nil, "path参数必须包含id")
		return
	}
	err = c.repository.Delete(classifyid)
	if err != nil {
		fmt.Println(err)
		response.Fail(ctx, nil, "删除失败")
		return
	}
	response.Success(ctx, nil, "删除成功")
	return
}

//Show 创建分类
func (c ClassifyController) Show(ctx *gin.Context) {
	//获取path中的参数
	classifyid, err := strconv.Atoi(ctx.Params.ByName("id"))
	if err != nil {
		response.Fail(ctx, nil, "path参数必须包含id")
	}
	exist, classify := c.repository.Select("id", classifyid)
	if !exist {
		response.Fail(ctx, nil, "分类不存在")
		return
	}
	fmt.Println(classify)
	response.Success(ctx, gin.H{"classify": classify}, "查询成功")

}
